package service

import (
	"log"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"github.com/lzppppppp/virapaksa-go/internal/system_monitor/handler"
	"github.com/lzppppppp/virapaksa-go/internal/system_monitor/model"
	"github.com/lzppppppp/virapaksa-go/internal/system_monitor/repository"
)

type NodeRegisterServiceData struct {
	Hostname string
	IP       string
	Type     string
	AppTeam  string
}

/*
 * 接收系统监控前端POST方法传送过来的注册服务需求
 * 解析数据，并注册服务
 */
func SystemRegisterService(context *gin.Context) {

	param := []NodeRegisterServiceData{}
	err := context.BindJSON(&param) // 接收前端数据，并返回状态
	if err != nil {
		context.JSON(500, gin.H{"err": err})
		return
	}

	dc2dc := map[string]string{ // 定义数据中心映射
		"北京数据中心":    "pek",
		"内蒙数据中心":    "nm",
		"上海数据中心":    "sh",
		"合肥数据中心":    "hf",
		"内蒙数据中心-和林": "nm-zj",
	}

	var cmdbDataArr []model.CmdbAllServer
	var dcArr []string
	for _, value := range param { // 根据前端数据查找数据库，并生成数据中心数组，用于不同的数据中心注册服务
		DB := repository.GetDB()
		var Data []model.CmdbAllServer
		DB.Table("cmdb_all_servers").Where("ip = ? AND hostname = ?", value.IP, value.Hostname).Find(&Data)
		cmdbDataArr = append(cmdbDataArr, Data[0])
		if !handler.Contains(dcArr, dc2dc[Data[0].Datacenter]) && Data[0].Datacenter != "" {
			dcArr = append(dcArr, dc2dc[Data[0].Datacenter])
		}
	}

	dcIndex := make(map[string]int)
	for _, dcValue := range dcArr { // 检查各数据中心，集群资源使用情况，返回最小集群
		dcIndex[dcValue] = handler.CheckServerVolume(dcValue)
		if dcIndex[dcValue] == 0 {
			log.Printf("ERROR: Prometheus server check failed.\n")
		}
	}

	var nodeRegOutCome string
	for index, cmdbData := range cmdbDataArr { // 注册服务
		serviceData := model.FuncServiceRegister{
			ExporterType: param[0].Type,
			Datacenter:   dc2dc[cmdbData.Datacenter],
			MinIndex:     strconv.Itoa(dcIndex[dc2dc[cmdbData.Datacenter]]),
			ShortName:    cmdbData.ShortName,
			Hostname:     cmdbData.Hostname,
			IP:           cmdbData.IP,
			AppTeam:      "系统平台服务部",
			ServiceName:  cmdbData.SystemName,
			SystemID:     strconv.Itoa(cmdbData.ProjectID),
		}
		log.Printf("INFO: Service data is %v.", serviceData)
		state := handler.ServiceRegisterSingle(index, serviceData)
		var reOutComeSingle string
		if state {
			reOutComeSingle = cmdbData.IP + ": " + param[0].Type + " service register success"
		} else {
			reOutComeSingle = cmdbData.IP + ": " + param[0].Type + " service register failed"
		}
		nodeRegOutCome = nodeRegOutCome + reOutComeSingle + "\n"
	}

	type jsonData struct {
		Code int
		Data string
	}
	data := jsonData{ // 返回前端信息
		Code: 200,
		Data: nodeRegOutCome,
	}
	context.JSON(http.StatusOK, data)
}
